var ws = null ;
var name = null;
var hisname = null;
var msg = null;
$(".nick_nick").modal({
	keyboard: true
});

$("#msg").keydown(function(event){
	if(event.which == 13){
		send();
	}
});

$("#nick").focus();

$("#nick").keydown(function(event){
	if(event.which == 13 ){
		client_login();
		$(".nick_nick").modal("hide");
	}
});

var login_info = function(name,info){
		$.postJSON(
			'/info',{
				obj:'{"type":"info","content":"'+name+' is '+ info +'","name":"'+name+'"}'
			},function(data){
				console.log(data);
				$('info_area').html('<div class="alert alert-info alert-animal " is_on="no"  onmouseout="animal_out(this)" onmouseover="animal_on(this)"  style="hight:50px;width:20%;" id="new_info">'+data+'</div>');
			}
		);
};

var client_login = function(){
		target = $("#ip").val();
		name = $("#nick").val();
		ws = new WebSocket("ws://"+target+"/noty");

		ws.onopen = function(){
			ws.send('{"type":"changeTag","tag":"'+name+'"}');
			$("#name").text(name);
			console.log("login");
			
			login_info(name,"online");
			user_info();
			$("#cmd").focus();
		};

		ws.onmessage = function(evt){
			console.log("msg");
			old = $("#new_info");
			old.attr({'id':'old'});
			data_str = evt.data.split('::');
			if (data_str.length == 3){
				new_ele = '<div class="alert alert-info alert-animal" is_on="no" onmouseout="animal_out(this)" onmouseover="animal_on(this)"  style="margin-left:7%";width:60%;" id="new_info"><code style="font-size:20sp;font-weight:100;margin-left:10px;margin-top:50px;margin-right:10px;width:50px" >'+data_str[1]+'</code>'+'<i><h3 style="font-weight:100">'+data_str[2]+'</h3></i><code>'+data_str[0]+'</code></div></div>';
			} else if( data_str.length == 4  ){
				new_ele = '<div class="alert alert-danger alert-animal" is_on="no" onmouseout="animal_out(this)" onmouseover="animal_on(this)" style="margin-left:3%;height:80px;width:30%;" id="new_info">'+'<i><h6 style="font-weight:100">'+data_str[2]+'</h6></i><code>'+data_str[0]+'</code><span class="label label-success" ><b>'+data_str[1]+'</b></span>'+data_str[3]+'</div>'; 
			}
			old.before(new_ele);
		};

		ws.onclose = function(){
			login_info(name,"off");
			console.log("close");
			$(".nick_nick").modal();
		}

		return ws;
}

